package cn.jingyuan.owl.enums.mybatis;

import cn.jingyuan.owl.enums.core.EnumInteger;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class EnumIntegerTypeHandler<E extends Enum<?> & EnumInteger> extends BaseTypeHandler<EnumInteger> {

    private final Class<E> type;

    public EnumIntegerTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, EnumInteger parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getCode());
    }

    @Override
    public EnumInteger getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int value = rs.getInt(columnName);
        return this.valueOf(value);
    }

    @Override
    public EnumInteger getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int value = rs.getInt(columnIndex);
        return this.valueOf(value);
    }

    @Override
    public EnumInteger getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int value = cs.getInt(columnIndex);
        return this.valueOf(value);
    }

    private E valueOf(int value) {
        try {
            return EnumInteger.valueOf(value, type);
        } catch (Exception ex) {
            throw new IllegalArgumentException("Cannot convert [" + value + "] to " + type.getSimpleName() + " by value value.", ex);
        }
    }

}
